import logging

import pymysql

from common.config import host
from common.doLog import DoLog

doLog=DoLog()
myLog=doLog.getLogger(__name__)

class DoDB():
    def __init__(self):
        try:
            #数据库连接对象
            self.db=pymysql.Connection(user='root',password='123456',
                                  host=host,
                                  port=3306,
                                  database='crm9',
                                  autocommit=True)


            #获取一个处理数据/执行sql语句的对象
            self.runner=self.db.cursor()
        except Exception as e:
            print(f'数据库连接,信息是:{e}')
            myLog.error(f'数据库连接,信息是:{e}')
        else:
            print('数据库连接成功')
            myLog.info('数据库连接成功')
        finally:
            print('数据库连接结束')
            myLog.info('数据库连接结束')



    def doselectSQL(self,sql):
        try:
            s=self.runner.execute(sql)
        except Exception as e:
            print(f'执行sql语句{sql}失败,信息是:{e}')
            myLog.error(f'执行sql语句{sql}失败,信息是:{e}')
        else:
            print('sql语句执行成功!')
            myLog.info('sql语句执行成功!')
            #获取数据：
            #获取所有：fetchall
            #获取一个：fetchone
            #获取部分：fetchmany
            s=self.runner.fetchall()
            # s=self.runner.fetchmany(10)

            # print(len(s),type(s),s,sep="\n")
            return s
        finally:
            self.runner.close()
            self.db.close()
            myLog.info('sql语句执行结束!')


if __name__ == '__main__':
    db=DoDB()
    sql="SELECT * FROM 72crm_oa_log;"
    t=db.doSQL(sql)
    # for i in t:
    #     print(i[0])


